package org.opengraphe.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Oauth
 */
public class Oauth extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Oauth() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String clientId = request.getParameter("client_id");
		if(clientId== null)
			clientId = "120059174683486";
		String code = request.getParameter("code");
		if(code != null){
			String url = "https://graph.facebook.com/oauth/access_token?client_id="+clientId+
			"&redirect_uri=http://localhost:8080/WebOpenGraph/oauth_redirect&"+
			"client_secret="+"b4ec2df60288b3dbdbfa353e0e2a1f57"+
			"&code="+code;
			URL ou = new URL(url);
			URLConnection uc = ou.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String inputLine = in.readLine();
			in.close();
			String accessCode = inputLine.split("&")[0].split("=")[1];
			response.getWriter().print(accessCode);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
